<template>
  <div>
    <div class="SHZY-full-dialog-header">
      <el-row :gutter="24" style="background-color: #F5F7FA;margin-bottom: 5px;">
        <el-col :span="12">
          <el-steps :active="activeStep" style="width: 400px;" finish-status="success" simple :class="'steps steps' + (maxStep + 1)"
            v-if="!loading">
            <el-step title="基础设置" @click.native="stepChick(0)" />
            <el-step title="表单设计" @click.native="stepChick(1)" />
          </el-steps>
        </el-col>
        <el-col :span="12" align="right" style="padding-top: 5px;padding-right: 15px;">
          <el-button @click="prev" :disabled="activeStep <= 0">{{ $t('common.prev') }}</el-button>
          <el-button @click="next1" :disabled="activeStep >= maxStep || loading">{{ $t('common.next') }}
          </el-button>
          <el-button type="primary" @click="dataFormSubmit()" :disabled="activeStep != maxStep" :loading="btnLoading">{{
            $t('common.confirmButton') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="main" v-loading="loading">
      <el-row type="flex" justify="center" align="middle" v-if="!activeStep" class="basic-box">
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="10" class="basicForm">
          <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px" @submit.native.prevent
            label-position="right">

            <el-table v-loading="listLoading" :data="mainTableFields" max-height="550" :row-class-name="tableRowClassName"
              empty-text="点击“新建属性”，添加至少一个属性">
              <el-table-column type="index" width="50" label="序号" align="center">
                <template slot-scope="scope">
                  {{ scope.$index - 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="fieldName" label="属性名">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.fieldName" placeholder="请输入属性名" />
                </template>
              </el-table-column>
              <!-- <el-table-column prop="field" label="列名">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.field" placeholder="请输入列名" maxlength="50" />
                        </template>
                    </el-table-column> -->
              <el-table-column prop="dataType" label="类型" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.dataType" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="dataLength" label="长度" width="150">
                <template slot-scope="scope">
                  <!-- <el-input v-model="scope.row.dataLength" placeholder="请输入长度"
                                :disabled="scope.row.dataType !== 'varchar' && scope.row.dataType !== 'decimal'" /> -->
                  <el-input-number v-model="scope.row.dataLength" controls-position="right" :min="1" :max="1000"
                    :disabled="scope.row.dataType !== 'varchar' && scope.row.dataType !== 'decimal'"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="50">
                <template slot-scope="scope">
                  <el-button class="SHZY-table-delBtn" size="mini" type="text"
                    @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-actions" @click="addHandle()">
              <el-button type="text" icon="el-icon-plus">新建属性</el-button>
            </div>
          </el-form>
        </el-col>
      </el-row>
      <template v-if="activeStep == 1">
        <Generator ref="generator" :conf="formData" :modelType="dataForm.type" :webType="dataForm.webType"
          :dbType="dbType" />
      </template>
      
    </div>
  </div>
</template>
  
<script>
// import { mapGetters } from 'vuex'
import Generator from '@/components/Generator/index/Home'
import mixin from '@/mixins/generator/form'
import { DataModelDelColumn } from '@/api/systemData/dataModel'
export default {
  mixins: [mixin],
  components: { Generator },
  data() {
    return {
      tableInfo: {
        table: '',
        tableName: '',
        newTable: ''
      },
      listLoading: false,
      refreshTable: true,
      list: [],
      options: [
        { label: '字符串', value: 'varchar' },
        { label: '整型', value: 'int' },
        { label: '日期时间', value: 'datetime' },
        { label: '浮点', value: 'decimal' },
        { label: '长整型', value: 'bigint' },
        { label: '文本', value: 'text' }
      ],
      dataRule: {
        fullName: [
          { required: true, message: '功能名称不能为空', trigger: 'blur' },
        ],
        enCode: [
          { required: true, message: '功能编码不能为空', trigger: 'blur' },
          { validator: this.formValidate('enCode'), trigger: 'blur' },
        ],
        category: [
          { required: true, message: '功能分类不能为空', trigger: 'change' },
        ]
      }
    }
  },
  // computed: {
  //   ...mapGetters(['userInfo']),
  // },
  created() {
    if (!this.dataForm.id) {
      this.dataForm = {
        id: '',
        fullName: '物料主数据自定义属性',
        enCode: 'materialCustomAttribute',
        type: 1,
        webType: 1,
        dbLinkId: '0',
        sortCode: 0,
        state: 1,
        category: '458835222654379717',// 自定义属性
        description: "物料主数据自定义属性",
        tables: ''
      }
      this.tableInfo.newTable = "qms_base_material_attr";
      this.tableInfo.tableName = "物料主数据自定义属性数据存储"
      this.relationTable = this.tableInfo.newTable;
      let index = this.mainTableFields.length, item = {}
      item = {
        field: "f_id",
        dataType: "varchar",
        dataLength: 50,
        allowNull: 0,
        fieldName: "主键",
        index,
        primaryKey: 1
      }
      this.mainTableFields.push(item)
      index = this.mainTableFields.length;
      item = {
        field: "f_foreignId",
        dataType: "varchar",
        dataLength: 50,
        allowNull: 0,
        fieldName: "外键",
        index,
        primaryKey: 0
      }
      this.mainTableFields.push(item)
    }
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (row.field == "f_id" || row.field == "f_foreignId") {
        return "hide-key-row"
      }
      return ""
    },
    next1() {
      if (this.mainTableFields.length <= 2) {
        this.$message({
          message: '请至少添加一个属性',
          type: 'error',
          duration: 1000
        })
        return
      }
      if (!this.exist1()) return
      if (this.tables.length) {
        this.tables[0].fields = [...this.mainTableFields]
      } else {
        this.tables.push({
          relationField: "",
          relationTable: "",
          table: this.tableInfo.newTable,
          tableName: this.tableInfo.tableName,
          tableField: '',
          typeId: "1",
          fields: [...this.mainTableFields]
        })
      }
      this.$nextTick(() => {
        this.next()
      })
    },
    handleDel(index, row) {
      if (row.newField) {
        this.mainTableFields.splice(index, 1)
      } else {
        this.$confirm('删除属性会把已保存的属性数据一并删除，是否继续？', '提示', {
          type: 'warning'
        }).then(() => {
          DataModelDelColumn(this.tables[0].table, row.field).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.mainTableFields.splice(index, 1)
              }
            })
          }).catch(() => { })
        }).catch(() => { });
      }
    },
    addHandle(row) {
      let index = this.mainTableFields.length, item = {}
      if (!row) {
        var timestamp = new Date().getTime();
        item = {
          field: "f_" + index.toString() + timestamp.toString(), dataType: "varchar", dataLength: 50, allowNull: 1, primaryKey: 0, fieldName: "", index, newField: "Y"
        }
      } else {
        item = {
          field: row.field,
          dataType: row.dataType,
          dataLength: row.dataLength,
          allowNull: row.allowNull,
          fieldName: row.fieldName,
          index,
          primaryKey: 0
        }
      }
      this.mainTableFields.push(item)
    },
    exist1() {
      let isOk = true;
      //  遍历数组，判断非空
      for (let i = 0; i < this.mainTableFields.length; i++) {
        const e = this.mainTableFields[i];
        if (!e.field) {
          this.$message({
            showClose: true,
            message: `第${i - 1}行列名不能为空`,
            type: 'error',
            duration: 1000
          });
          isOk = false
          break
        }
        let num = this.mainTableFields.filter(o => o.field == e.field)
        if (num.length > 1) {
          this.$message({
            showClose: true,
            message: `第${i - 1}行列名'${e.field}'已重复`,
            type: 'error',
            duration: 1000
          });
          isOk = false
          break
        }
        if (!e.fieldName) {
          this.$message({
            showClose: true,
            message: `第${i - 1}行属性名不能为空`,
            type: 'error',
            duration: 1000
          });
          isOk = false
          break
        }
      }
      return isOk;
    }

  }
}
</script>
<style>
.hide-key-row {
  display: none;
}
</style>